package st.business.tepth.business.businfo;

import android.app.DatePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.business.bean.BusDriverInfoBean;
import st.business.tepth.business.driverinfo.DriverInfoDelegate;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.indicator.magicindicator.MagicIndicator;
import st.shadow.library.ui.indicator.magicindicator.ViewPagerHelper;
import st.shadow.library.ui.indicator.magicindicator.buildins.UIUtil;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.CommonNavigator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-02-27 10:33
 * 车辆信息
 */

public class BusInfoDelegate
        extends MvpFragment<BusInfoPresenter> implements BusInfoContract.View {
    public static BusInfoDelegate newInstance(int id) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", id);
        BusInfoDelegate delegate = new BusInfoDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    @BindView(R2.id.indicator)
    MagicIndicator mIndicator;
    @BindView(R2.id.view_pager)
    ViewPager mViewPager;
    @BindView(R2.id.tv_right_button)
    TextView mRightButton;
    @BindView(R2.id.et_date_start)
    TextView mTvDateStart;
    @BindView(R2.id.et_date_end)
    TextView mTvDateEnd;
    @BindView(R2.id.tv_bus_licence)
    TextView mTvLicence;
    @BindView(R2.id.tv_bus_company)
    TextView mTvCompany;
    @BindView(R2.id.tv_register_time)
    TextView mTvRegisterTime;
    @BindView(R2.id.tv_bus_type)
    TextView mTvBusType;
    @BindView(R2.id.tv_bus_number)
    TextView mTvBusNumber;
    @BindView(R2.id.tv_driver_name)
    TextView mTvDriverName;
    @BindView(R2.id.tv_in_factory)
    TextView mTvInFactory;
    @BindView(R2.id.tv_distance)
    TextView mTvDistance;
    @BindView(R2.id.layout_content)
    ConstraintLayout mLayoutContent;
    @BindView(R2.id.tv_gas_use)
    TextView mTvGasUse;
    @BindView(R2.id.tv_oil_use)
    TextView mTvOilUse;
    @BindView(R2.id.tv_last_mileage)
    TextView mTvLastMileage;
    @BindView(R2.id.tv_total_mileage)
    TextView mTvTotalMileage;
    private int mRepairId;
    private int mCurrentIndex = 0;
    private String mBusNumber;
    private List<Fragment> mFragments = new ArrayList<>();

    private BusDriverInfoBean mBusDriverInfoBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
        }
    }

    @Override
    public BusInfoPresenter getPresenter() {
        return new BusInfoPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_bus_info;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        addTopView(R.layout.view_loading, mLayoutContent);
        mTvTitle.setText("查看车辆信息");
        mRightButton.setText("查看司机");
        mFragments.add(FragmentWorkHistory.newInstance());
        mFragments.add(FragmentWarnHistory.newInstance());
        mViewPager.setAdapter(new BusPagerAdapter(getChildFragmentManager(), mFragments));

        CommonNavigator commonNavigator = new CommonNavigator(_mActivity);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return 2;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ClipPagerTitleView clipPagerTitleView = new ClipPagerTitleView(context);
                clipPagerTitleView.setText(index == 0 ? "作业记录" : "报警记录");
                clipPagerTitleView.setTextColor(Color.parseColor("#8fa3b7"));
                clipPagerTitleView.setClipColor(Color.parseColor("#333333"));
                clipPagerTitleView.setTextSize(22);
                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                        mCurrentIndex = index;
                    }
                });
                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                float navigatorHeight = context.getResources()
                        .getDimension(R.dimen.common_navigator_height);
                float borderWidth = UIUtil.dip2px(context, 1);
                float lineHeight = navigatorHeight - 2 * borderWidth;
                indicator.setLineHeight(lineHeight);
                indicator.setRoundRadius(2);
                indicator.setYOffset(borderWidth);
                indicator.setColors(Color.parseColor("#f1b647"));
                return indicator;
            }
        });
        mIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mIndicator, mViewPager);
        mPresenter.getBusInfo(UserManager.getInstance().getToken(), mRepairId);
    }

    @OnClick(R2.id.tv_right_button)
    public void onWatchDriverInfo() {

    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    @OnClick(R2.id.et_date_start)
    public void onChooseDateStart() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateStart.setText(date);
                        mTvDateStart.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @OnClick(R2.id.et_date_end)
    public void onChooseDateEnd() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateEnd.setText(date);
                        mTvDateEnd.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @OnClick(R2.id.iv_search)
    public void onSearch() {
        Fragment fragment = mFragments.get(mCurrentIndex);
        if (mCurrentIndex == 0) {
            ((FragmentWorkHistory) fragment)
                    .search(mBusNumber, "请选择开始日期"
                                    .equals(mTvDateStart.getText().toString()) ? "" :
                                    mTvDateStart.getText().toString(),
                            "请选择结束日期".equals(mTvDateEnd.getText().toString()) ?
                                    "" : mTvDateEnd.getText().toString());
        } else {
            ((FragmentWarnHistory) fragment)
                    .search(mBusNumber, "请选择开始日期"
                                    .equals(mTvDateStart.getText().toString()) ? "" :
                                    mTvDateStart.getText().toString(),
                            "请选择结束日期".equals(mTvDateEnd.getText().toString()) ?
                                    "" : mTvDateEnd.getText().toString());
        }
    }

    @OnClick(R2.id.tv_right_button)
    public void showDriverInfo() {
        if (mBusDriverInfoBean != null) {
            BusDriverInfoBean.BusInfoBean busInfoBean =
                    mBusDriverInfoBean.getBusInfo();
            BusDriverInfoBean.DriverInfoBean driverInfoBean =
                    mBusDriverInfoBean.getDriverInfo();
            if (busInfoBean != null && driverInfoBean != null) {
                start(DriverInfoDelegate.newInstance(driverInfoBean.getName(),
                        driverInfoBean.getPhone(), driverInfoBean.getJobNo(),
                        busInfoBean.getNo(), busInfoBean.getCompany()));
            } else {
                ToastUtils.showShort("无司机相关信息");
            }


        } else {
            ToastUtils.showShort("无司机相关信息");
        }

    }

    @Override
    public void showData(BusDriverInfoBean busDriverInfoBean) {
        mBusDriverInfoBean = busDriverInfoBean;
        removeTopView(mLayoutContent);
        if (busDriverInfoBean != null) {
            BusDriverInfoBean.BusInfoBean busInfoBean =
                    busDriverInfoBean.getBusInfo();
            BusDriverInfoBean.DriverInfoBean driverInfoBean =
                    busDriverInfoBean.getDriverInfo();
            if (busInfoBean != null) {
                mBusNumber = busInfoBean.getNo();
                mTvLicence.setText(busInfoBean.getLicence());
                mTvCompany.setText(String.format("所属公司：%s", busInfoBean.getCompany()));
                mTvRegisterTime.setText(String.format("登记日期：%s", busInfoBean.getRegister()));
                mTvBusType.setText(String.format("车辆型号：%s", busInfoBean.getType()));
                mTvBusNumber.setText(String.format("车辆编号：%s", busInfoBean.getNo()));
                mTvInFactory.setText(String.format("进厂时间：%s", busInfoBean.getInFacotry()));
                mTvDistance.setText(String.format("距离：%s", busInfoBean.getDistance()));
                String gasType = busInfoBean.getFuelType();
                String fuelPerKm = busInfoBean.getFuelPerKm();
                String engineOil = busInfoBean.getEngineOil();
                String kmAfterLastVm = busInfoBean.getKmAfterLastVm();
                String kmTotal = busInfoBean.getKmTotal();
                mTvGasUse.setText(String.format("上月%s耗量：%s", gasType, fuelPerKm));
                mTvOilUse.setText(String.format("上月机油耗量：%s", engineOil));
                mTvLastMileage.setText(String.format("距上次保养里程：%s", kmAfterLastVm));
                mTvTotalMileage.setText(String.format("总里程：%s", kmTotal));
            }
            if (driverInfoBean != null) {
                mTvDriverName.setText(String.format("司机：%s", driverInfoBean.getName()));
            }
            onSearch();
        } else {
            addTopView(R.layout.view_search_empty, mLayoutContent);
        }
    }

    @Override
    public void showError(String msg) {
        removeTopView(mLayoutContent);
        addTopView(R.layout.view_search_empty, mLayoutContent);
    }

    public void startNewFragment(ISupportFragment fragment) {
        start(fragment);
    }
}